#!/bin/bash -e

declare _mydir=$(dirname $0)
source "${_mydir}"/env.rc
source "${_mydir}"/util.rc

main() {

    if [ -f "${_build_context}/${_scrap_demand_stop_building}" ] ; then
        echo "Skipping build on demand."
        return 0
    fi

    local now
    local version_sticker

    if [ -f "${_build_context}/${_scrap_version_sticker_current}" ] ; then
        version_sticker="$( cat ${_build_context}/${_scrap_version_sticker_current} )"
    else
        version_sticker="null"
    fi

    now="$(date --utc +%FT%TZ)"
    echo "Current timestamp: ${now}" ; echo

    set -x
    docker build $@ \
        -f "${DOCKERFILE_PATH}" \
            --build-arg BUILDKIT_INLINE_CACHE=1 \
            --build-arg BASEIMAGE="${BASEIMAGE}" \
            --build-arg BASETAG="${BASETAG}" \
            --build-arg ARG_CREATED="${now}" \
            --build-arg ARG_DOCKER_TAG=${DOCKER_TAG} \
            --build-arg ARG_VERSION_STICKER="${version_sticker}" \
            --build-arg ARG_VCS_REF="$(git rev-parse --short HEAD)" \
            \
            ${FEATURES_BUILD_SLIM:+--build-arg ARG_APT_NO_RECOMMENDS=1} \
            ${FEATURES_SCREENSHOOTING:+--build-arg ARG_FEATURES_SCREENSHOOTING=1} \
            ${FEATURES_THUMBNAILING:+--build-arg ARG_FEATURES_THUMBNAILING=1} \
            ${FEATURES_USER_GROUP_OVERRIDE:+--build-arg ARG_FEATURES_USER_GROUP_OVERRIDE=1} \
            \
            ${FEATURES_NOVNC:+--build-arg ARG_MERGE_STAGE_VNC_BASE="stage_novnc"} \
            \
            ${FEATURES_CHROMIUM:+--build-arg ARG_CHROMIUM_VERSION=${CHROMIUM_VERSION}} \
            ${FEATURES_CHROMIUM:+--build-arg ARG_MERGE_STAGE_BROWSER_BASE="stage_chromium"} \
            \
            ${FEATURES_FIREFOX:+--build-arg ARG_MERGE_STAGE_BROWSER_BASE="stage_firefox"} \
            ${FEATURES_FIREFOX_PLUS:+--build-arg ARG_MERGE_STAGE_BROWSER_BASE="stage_firefox_plus"} \
            \
        -t "${DOCKER_REPO}":"${DOCKER_TAG}" "${_build_context}"
    set +x
}

main $@
